package com.lanyou.esb.cook.proxy.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lanyou.esb.cook.proxy.common.Constants;
import com.lanyou.esb.cook.proxy.common.SystemResCode;
import com.lanyou.esb.cook.proxy.entity.Token;
import com.lanyou.esb.cook.proxy.exception.AuthException;
import com.lanyou.esb.cook.proxy.meta.Environment;
import com.lanyou.esb.cook.proxy.service.AuthService;
import com.lanyou.esb.cook.proxy.vo.AccTokenResult;
import com.lanyou.esb.cook.proxy.vo.ErrorMsg;

/**
 * 授权服务
 * 
 * @author Davey.wu
 */
public class AccTokenServlet extends HttpServlet {
	/****/
	private static final long serialVersionUID = 3670012249806136525L;
	/** 权限验证服务接口 **/
	private AuthService authService;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding(Constants.ENCODING_TYPE_UTF8);
		// 密钥
		String applyKey = getValue(request, Constants.APPLY_KEY);
		// 系统编码
		String systemCode = getValue(request, Constants.SYSTEM_CODE);
		// 接口编码
		String ifCode = getValue(request, Constants.INTERFACE_CODE);
		// 接口版本
		String ifVersion = getValue(request, Constants.INTERFACE_VERSION);
		try {
			// 密钥不能为空
			if (StringUtils.isEmpty(applyKey)) {
				throw new AuthException(SystemResCode.MSG_APPLYKEY_EMPTY,
						SystemResCode.CODE_APPLYKEY_EMPTY);
			}
			// 系统编码不能为空
			if (StringUtils.isEmpty(systemCode)) {
				throw new AuthException(SystemResCode.MSG_PUB_SYSTEMCODE_EMPTY,
						SystemResCode.CODE_PUB_SYSTEMCODE_EMPTY);
			}
			// 接口编码不能为空
			if (StringUtils.isEmpty(ifCode)) {
				throw new AuthException(SystemResCode.MSG_INTERFACECODE_EMPTY,
						SystemResCode.CODE_INTERFACECODE_EMPTY);
			}
			// 接口版本不能为空
			if (StringUtils.isEmpty(ifVersion)) {
				throw new AuthException(
						SystemResCode.MSG_INTERFACEVERSION_EMPTY,
						SystemResCode.CODE_INTERFACEVERSION_EMPTY);
			}
			// 授权
			Token token = authService.authenticate(applyKey, systemCode,
					ifCode, ifVersion, Environment.PRODUCTION);
			AccTokenResult result = new AccTokenResult(token.getAccessToken(),
					token.getInvalidTimes());
			ObjectMapper mapper = new ObjectMapper();
			String json = "";
			try {
				json = mapper.writeValueAsString(result);
			} catch (JsonProcessingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			response(response, json);
		} catch (AuthException e) {
			ErrorMsg errorMsg = new ErrorMsg();
			errorMsg.setErrorCode(e.getCode());
			errorMsg.setErrorDesc(e.getMessage());
			ObjectMapper mapper = new ObjectMapper();
			String json = "";
			try {
				json = mapper.writeValueAsString(errorMsg);
			} catch (JsonProcessingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			response(response, json);
		} catch (Exception e) {
			ErrorMsg errorMsg = new ErrorMsg();
			errorMsg.setErrorCode(SystemResCode.CODE_OTHER_EXCEPTION);
			errorMsg.setErrorDesc(e.toString() + ":" + e.getMessage());
			ObjectMapper mapper = new ObjectMapper();
			String json = "";
			try {
				json = mapper.writeValueAsString(errorMsg);
			} catch (JsonProcessingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			response(response, json);
		}
	}

	/**
	 * 获取请求参数
	 * 
	 * @param request
	 *            ：请求对象
	 * @param name
	 *            ：参数名
	 * @return
	 */
	private String getValue(HttpServletRequest request, String name) {
		String value = request.getHeader(name);
		if (!(StringUtils.isEmpty(value))) {
			return value;
		}
		return request.getParameter(name);
	}

	/**
	 * 设置请求响应
	 * 
	 * @param response
	 *            ：响应对象
	 * @param json
	 *            ：响应报文
	 */
	private void response(HttpServletResponse response, String json) {
		response.setContentType(Constants.CONTENT_TYPE_APP_JSON);
		response.setCharacterEncoding(Constants.ENCODING_TYPE_UTF8);
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.append(json.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}

	}

	public AuthService getAuthService() {
		return authService;
	}

	public void setAuthService(AuthService authService) {
		this.authService = authService;
	}

}
